<?php

declare(strict_types=1);

namespace app\model;

use app\common\TextFormat;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class UserRecord extends Model
{
  //

  use SoftDelete;

  protected $defaultSoftDelete = 0;

  public function getContentHtmlAttr()
  {
    $type = $this->getData('type');

    $content = $this->getAttr('content');
    if ($type == 'user_message') {
      $model_user = User::find($this->getData('from_user_id'));

      $content = TextFormat::p(
        TextFormat::a(url("User/index", ['id' => $model_user->id]), $model_user->nickname)
          . '给您发送消息:'
          . TextFormat::br($content)
      );
    } else if ($type == 'new_post') {
      $model_post = Post::find($this->getData('target_id'));

      $content = TextFormat::p(
        '新发表了文章'
          . TextFormat::a(url('Post/read', ['id' => $model_post->id]), $model_post->title)
      );
    }


    return $content;
  }

  public function getCreateTimeFormatAttr()
  {
    $time = $this->getData('create_time');

    return time_tran(date('Y-m-d H:i:s', $time));
  }

  public static function buildAndSave($type, $target_id, $target_user_id, $from_user_id = 0, $content = '')
  {
    $model_record = new UserRecord();

    $model_record->set('type', $type);

    $model_record->target_id = $target_id;
    $model_record->target_user_id = $target_user_id;

    $model_record->from_user_id = $from_user_id;
    $model_record->content = $content;
    $model_record->save();
    return $model_record;
  }
}
